﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using Newtonsoft.Json;
using VegetableStoreBackJob.JsonObject;
using VegetableStoreBackJob.Domains;
using NHibernate;
using VegetableStoreBackJob.Providers;
using System.Globalization;

namespace VegetableStoreBackJob
{
    public partial class Form1 : Form
    {
        private ISession nhibernateSession;
        WebClient webClient;
        
        public Form1()
        {
            InitializeComponent();
            nhibernateSession = SessionProvider.Instance.GetSession();
            webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
        }

        private void btnGetProductPrice_Click(object sender, EventArgs e)
        {
            string url = "http://openAPI.seoul.go.kr:8088/6a756e67726f34323532313533/json/ListNecessariesPricesService/1/12000";
                        
            var json = webClient.DownloadString(url);

            ProductRoot rootJson = JsonConvert.DeserializeObject<ProductRoot>(json);
            int dataSize = rootJson.ListNecessariesPricesService.list_total_count;
            IList<Product> productList = rootJson.ListNecessariesPricesService.row;
            InsertStandardProducts(productList, dataSize);
        }

        private void InsertStandardProducts(IList<Product> productList, int dataSize)
        {
            foreach (Product product in productList)
            {
                try
                {
                    object[] priceAndUnit = SplitUnitAndQuantity(product.A_UNIT);
                    int unitQuantity = (int)priceAndUnit[0];
                    string unit = priceAndUnit[1].ToString();

                    Standardproduct standardProduct = nhibernateSession.Get<Standardproduct>(product.A_SEQ);
                    if (product.M_TYPE_CODE == "002") //대형마트라면
                    {
                        if (standardProduct == null) // 신규 
                        {
                            standardProduct = new Standardproduct
                            {
                                Id = product.A_SEQ,
                                ProductcategoryId = 8,
                                Name = product.A_NAME,
                                Unit = unit,
                                UnitQuantity = unitQuantity,
                                Price = product.A_PRICE,
                                MartName = product.M_NAME,
                                RegistrationDate = product.P_DATE.ToString("yyyyMMdd")
                            };
                        }
                        else //업데이트
                        {
                            DateTime registrationDate = DateTime.ParseExact(standardProduct.RegistrationDate, "yyyyMMdd", CultureInfo.InvariantCulture);
                            if (registrationDate <= product.P_DATE) // 더 최신데이터인 경우
                            {
                                if (standardProduct.Price < product.A_PRICE) // 가격이 더 높은 경우
                                {
                                    standardProduct.Unit = unit;
                                    standardProduct.UnitQuantity = unitQuantity;
                                    standardProduct.Price = product.A_PRICE;
                                    standardProduct.MartName = product.M_NAME;
                                    standardProduct.RegistrationDate = product.P_DATE.ToString("yyyyMMdd");
                                }
                            }
                        }

                        nhibernateSession.SaveOrUpdate(standardProduct);
                        nhibernateSession.Flush();
                    }
                }
                catch (Exception e)
                {

                }                
            }
        }

        private object[] SplitUnitAndQuantity(string unitAndQuantity)
        {
            int quantity = 0;
            string unit = "";
            int unitStartIndex = 0;
           
            for (int i = 0; i < unitAndQuantity.Length; i++)
            {
                if (!int.TryParse(unitAndQuantity.Substring(0, i+1), out quantity))
                {
                    quantity = int.Parse(unitAndQuantity.Substring(0,i));
                    unitStartIndex = i;
                    unit = unitAndQuantity.Substring(i, unitAndQuantity.Length-i);
                    break;
                }                
            }
            for (int i = unitStartIndex; i < unitAndQuantity.Length; i++)
            {
                if (unitAndQuantity[i] == '(')
                {
                    unit = unitAndQuantity.Substring(unitStartIndex, i-unitStartIndex);
                    break;
                }
            }
            return new object[] { quantity, unit };
        }

        private void btnGetMarket_Click(object sender, EventArgs e)
        {
            string url = "http://openAPI.seoul.go.kr:8088/6a756e67726f34323532313533/json/ListTraditionalMarket/1/350";

            var json = webClient.DownloadString(url);

            TraditionalMarketRoot rootJson = JsonConvert.DeserializeObject<TraditionalMarketRoot>(json);
            int dataSize = rootJson.ListTraditionalMarket.list_total_count;
            IList<TraditionalMarket> traditionalMarketList = rootJson.ListTraditionalMarket.row;
            InsertMarket(traditionalMarketList, dataSize);
            
        }

        private void InsertMarket(IList<TraditionalMarket> traditionalMarketList, int dataSize)
        {
            foreach (TraditionalMarket traditionalMarket in traditionalMarketList)
            {
                Address address = nhibernateSession.QueryOver<Address>()
                    .Where(x => x.Sigungu == traditionalMarket.GUNAME)
                    .List()
                    .FirstOrDefault();
                Market market = new Market
                {
                    Address = address,
                    Name = traditionalMarket.M_NAME
                };
                nhibernateSession.SaveOrUpdate(market);
                nhibernateSession.Flush();
            }
        }
    }
}
